package com.yami.shop.config;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.yami.shop.bean.app.param.PayXsCountOrderParam;
import com.yami.shop.bean.app.param.PersonalAccountOpenParam;
import com.yami.shop.bean.app.param.XsQueryParam;
import com.yami.shop.bean.bo.PayInfoResultBO;
import com.yami.shop.bean.model.PayInfo;
import com.yami.shop.bean.model.UserXsCard;
import com.yami.shop.bean.param.EnterpriseAccountOpeningParam;
import com.yami.shop.bean.param.EnterpriseChangeCardParam;
import com.yami.shop.bean.param.EnterpriseChangeInfoParam;
import com.yami.shop.bean.param.hnaPay.*;
import com.yami.shop.bean.pay.PayInfoDto;
import com.yami.shop.bean.pay.RefundInfoDto;
import com.yami.shop.bean.pay.WithdrawalDto;
import com.yami.shop.common.bean.HnaPay;
import com.yami.shop.common.util.Base64Utils;
import com.yami.shop.common.util.IPHelper;
import com.yami.shop.common.util.hnaPay.HnapaySign;
import com.yami.shop.common.util.hnaPay.HttpClientUtils;
import com.yami.shop.common.util.hnaPay.HttpsTransport;
import com.yami.shop.common.util.hnaPay.KeyUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
@AllArgsConstructor
public class HnaPayConfig {
    private final ShopConfig shopConfig;
    // 提现
    public static final String T002_SUBMIT_URL = "https://ncount.hnapay.com/api/t002.htm";
    // 转账
    public static final String T003_SUBMIT_URL = "https://ncount.hnapay.com/api/t003.htm";
    // 快捷支付下单
    public static final String T007_SUBMIT_URL = "https://ncount.hnapay.com/api/t007.htm";
    // 快捷支付确认
    public static final String T008_SUBMIT_URL = "https://ncount.hnapay.com/api/t008.htm";
    // H5支付 目前只支持支付宝及云闪付
    public static final String T013_SUBMIT_URL = "https://ncount.hnapay.com/api/t013.htm";
    // 微信公众号/支付宝生活号支付接口
    public static final String T006_SUBMIT_URL = "https://ncount.hnapay.com/api/t006.htm";
    // 退款
    public static final String T005_SUBMIT_URL = "https://ncount.hnapay.com/api/t005.htm";
    // 交易查询
    public static final String Q002_SUBMIT_URL = "https://ncount.hnapay.com/api/q002.htm";
    // 个人开户
    public static final String R010_SUBMIT_URL = "https://ncount.hnapay.com/api/r010.htm";
    // 用户查询
    public static final String Q001_SUBMIT_URL = "https://ncount.hnapay.com/api/q001.htm";
    // 用户账户明细
    public static final String Q004_SUBMIT_URL = "https://ncount.hnapay.com/api/q004.htm";
    // 绑卡
    public static final String R007_SUBMIT_URL = "https://ncount.hnapay.com/api/r007.htm";
    // 绑卡确认
    public static final String R008_SUBMIT_URL = "https://ncount.hnapay.com/api/r008.htm";
    // 个人用户解绑
    public static final String R009_SUBMIT_URL = "https://ncount.hnapay.com/api/r009.htm";
    // 企业用户换卡
    public static final String R002_SUBMIT_URL = "https://ncount.hnapay.com/api/r002.htm";

    // 企业开户
    public static final String R001_SUBMIT_URL = "https://ncount.hnapay.com/api/r001.htm";
    // 企业开户上送资料
    public static final String R003_SUBMIT_URL = "https://ncount.hnapay.com/api/r003.htm";
    // 企业信息修改
    public static final String R011_SUBMIT_URL = "https://ncount.hnapay.com/api/r011.htm";
    // 收货确认
    public static final String F001_SUBMIT_URL = "https://ncount.hnapay.com/api/f001.htm";

    public T002TransForm getT002TransForm(WithdrawalDto withdrawalDto) {
        T002TransForm transForm = new T002TransForm();
        transForm.setTranCode("T002");
        transForm.initCommonParams("T002", shopConfig.getHnaPay().getMerId(), withdrawalDto.getWithdrawCashId());
        transForm.setSubmitUrl(T002_SUBMIT_URL);
        transForm.setTranAmount(withdrawalDto.getTranAmount());
        transForm.setUserId(withdrawalDto.getXsUserId());
        transForm.setNotifyUrl(withdrawalDto.getWithdrawalNoticeUrl());
        // 08：协议号提现（默认）；09：同名非绑卡提现；
        transForm.setBusinessType(withdrawalDto.getBusinessType());
        if (withdrawalDto.getBusinessType().equals("08")) {
            transForm.setBindCardAgrNo(withdrawalDto.getBindCardAgrNo());
        }
        if (withdrawalDto.getBusinessType().equals("09")) {
            transForm.setCardNo(withdrawalDto.getCardNo());
        }
        // 服务费
        transForm.setServiceAmount(withdrawalDto.getServiceAmount());
        // 付款方终端信息
        if (ObjectUtil.isNotNull(withdrawalDto.getPaymentTerminalInfo())) {
            transForm.setPaymentTerminalInfo(withdrawalDto.getPaymentTerminalInfo());
        } else {
            String paymentTerminalInfo = "02|";
            transForm.setPaymentTerminalInfo(paymentTerminalInfo);
        }
        // 设备信息
        if (ObjectUtil.isNotNull(withdrawalDto.getDeviceInfo())) {
            transForm.setDeviceInfo(withdrawalDto.getDeviceInfo());
        } else {
            String deviceInfo = IPHelper.getIpAddr() + "||||||";
            transForm.setDeviceInfo(deviceInfo);
        }
        return transForm;
    }


    /**
     * 新生转账
     *
     * @param payInfo payInfo
     * @return
     */
    public T003TransForm getT003TransForm(PayInfoDto payInfo) {
        T003TransForm transForm = new T003TransForm();
        transForm.setTranCode("T003");
        transForm.initCommonParams("T003", shopConfig.getHnaPay().getMerId(), payInfo.getPayNo());
        transForm.setSubmitUrl(T003_SUBMIT_URL);
        // 转账金额
        transForm.setTranAmount(payInfo.getPayAmount().toString());
        // 付款方用户编号
        transForm.setPayUserId(payInfo.getPayUserId());
        // 收款方ID
        transForm.setReceiveUserId(payInfo.getReceiveUserId());
        // 业务类型 02转账，默认02
        transForm.setBusinessType("02");
        return transForm;
    }

    /**
     * H5支付 目前只支持支付宝及云闪付
     *
     * @param payInfo payInfo
     * @return T013TransForm
     */
    public T013TransForm getT013TransForm(PayInfoDto payInfo, String notifyUrl) throws Exception {
        T013TransForm transForm = new T013TransForm();
        transForm.setTranCode("T013");
        transForm.initCommonParams("T013", shopConfig.getHnaPay().getMerId(), payInfo.getPayNo());
        transForm.setSubmitUrl(T013_SUBMIT_URL);
        transForm.setTranAmount(payInfo.getPayAmount().toString());
        // 交易币种 1：人民币（默认）
        transForm.setCurrencyType("1");
        // 商户前台通知地址
        transForm.setNotifyFrontUrl(payInfo.getReturnUrl());
        // 商户异步通知地址
        transForm.setNotifyServerUrl(notifyUrl);
        // 商品信息
        transForm.setGoodsInfo(payInfo.getBody());
        // 订单标题
        transForm.setOrderSubject(payInfo.getOrderSubject());
        // 业务类型 03：消费（默认） 04：担保下单
        transForm.setBusinessType(payInfo.getBusinessType());
        // 客户机构号
        if (payInfo.getPayType() == 11) {
            // HnaZFB为支付宝支付直联模式；
            transForm.setPayType("HnaZFB");
            // 客户机构号	1-30
            log.info("shopConfig.getHnaPay().getMerchantAliId()========================================{}",shopConfig.getHnaPay().getMerchantAliId());
            // if(ObjectUtil.isNull(payInfo.getMerchantId())){
            //     throw new Exception("支付宝进件报备编号为空!");
            // }
            // transForm.setMerchantId(payInfo.getMerchantId());
            transForm.setMerchantId(shopConfig.getHnaPay().getMerchantAliId());
        }
        if (payInfo.getPayType() == 12) {
            // HnaYSF 为云闪付直联模式；
            transForm.setPayType("HnaYSF");
            // 客户机构号	1-30
            transForm.setMerchantId(shopConfig.getHnaPay().getMerchantYsfId());
        }
        // 交易IP
        transForm.setMerUserIp(IPHelper.getIpAddr());
        // 收款方ID 消费交易时，填收款方ID 担保交易时，填商户ID 默认担保交易
        transForm.setReceiveUserId(payInfo.getReceiveUserId());
        //订单过期时间 数字（单位分钟）最大1天，24*60分钟
        transForm.setExpireTime("3");

        // 担保下单 分账明细与手续费承担方id必填
        if (payInfo.getBusinessType().equals("04")) {
            log.info("payInfo.getBusinessType()========================================{}",payInfo.getBusinessType());
            // 担保下单
            if (ObjectUtil.isNull(payInfo.getDivideAcctDtlList())) {
                throw new Exception("分账信息为空!");
            }
            transForm.setDivideAcctDtl(payInfo.getDivideAcctDtlList());
            // 续费承担方id
            transForm.setFeeAmountUser(shopConfig.getHnaPay().getMerId());
            // 手续费内扣外扣 0：外扣（消费默认，担保时需单独申请）1：内扣（担保默认，消费时需单独申请）
            transForm.setFeeType("1");
        }
        return transForm;
    }

    /**
     * 微信公众号/支付宝生活号支付接口
     *
     * @param payInfo   payInfo
     * @param notifyUrl notifyUrl
     * @return T006TransForm
     * @throws Exception Exception
     */
    public T006TransForm getT006TransForm(PayInfoDto payInfo, String notifyUrl) throws Exception {
        T006TransForm transForm = new T006TransForm();
        transForm.setTranCode("T006");
        transForm.initCommonParams("T006", shopConfig.getHnaPay().getMerId(), payInfo.getPayNo());
        transForm.setSubmitUrl(T006_SUBMIT_URL);
        transForm.setTranAmount(payInfo.getPayAmount().toString());
        // 币种
        transForm.setCurrencyType("1");
        // 备注
        transForm.setRemark(payInfo.getBody());
        transForm.setNotifyServerUrl(notifyUrl);
        // 用户浏览器IP
        transForm.setMerUserIp(IPHelper.getIpAddr());
        // 商品信息
        transForm.setGoodsInfo(payInfo.getBody());
        // 订单标题
        transForm.setOrderSubject(payInfo.getOrderSubject());
        // 订单描述
        transForm.setOrderDesc(payInfo.getBody());
        // 业务类型 03：消费（默认） 04：担保下单
        transForm.setBusinessType(payInfo.getBusinessType());
        // 担保下单 分账明细与手续费承担方id必填 03消费时收款方ID必填
        if (payInfo.getBusinessType().equals("04")) {
            // 担保下单
            if (ObjectUtil.isNull(payInfo.getDivideAcctDtlList())) {
                throw new Exception("分账信息为空!");
            }
            transForm.setDivideAcctDtl(payInfo.getDivideAcctDtlList());
            // 续费承担方id
            transForm.setFeeAmountUser(shopConfig.getHnaPay().getMerId());
            // 手续费内扣外扣 0：外扣（消费默认，担保时需单独申请）1：内扣（担保默认，消费时需单独申请）
            transForm.setFeeType("1");
        }
        if (payInfo.getPayType() == 13) {
            // 公众号appID
            transForm.setAppId(shopConfig.getHnaPay().getWxAppId());
            // 买家微信openid
            transForm.setOpenId(payInfo.getBizUserId());
            // 目标资金机构代码 WECHATPAY:微信公众号支付 ALIPAY:支付宝生活号支付
            transForm.setOrgCode("WECHATPAY");
        }
        if (payInfo.getPayType() == 14) {
            // 商家支付宝生活号ID
            transForm.setAliAppId(shopConfig.getHnaPay().getAliAppId());
            // 买家支付宝账号
            transForm.setBuyerLogonId(payInfo.getBizUserId());
            // 目标资金机构代码 WECHATPAY:微信公众号支付 ALIPAY:支付宝生活号支付
            transForm.setOrgCode("ALIPAY");
        }
        // 客户机构号
        transForm.setMerchantId(shopConfig.getHnaPay().getMerchantJspId());
        // 收款方ID
        transForm.setReceiveUserId(payInfo.getReceiveUserId());

        return transForm;
    }

    /**
     * 快捷支付下单
     *
     * @param payInfo   payInfo
     * @param notifyUrl notifyUrl
     * @return T007TransForm
     */
    public T007TransForm getT007TransForm(PayInfoDto payInfo, String notifyUrl) {
        T007TransForm transForm = new T007TransForm();
        transForm.setTranCode("T007");
        transForm.initCommonParams("T007", shopConfig.getHnaPay().getMerId(), payInfo.getPayNo());
        transForm.setSubmitUrl(T007_SUBMIT_URL);
        transForm.setTranAmount(payInfo.getPayAmount().toString());
        // 支付方式 2:银行卡卡号 3:绑卡协议号
        transForm.setPayType(payInfo.getXsFastPaymentOneParam().getPayWay().toString());
        // 银行卡卡号支付
        if (payInfo.getXsFastPaymentOneParam().getPayWay() == 2) {
            // 支付银行卡卡号 payType=2不可空
            transForm.setCardNo(payInfo.getXsFastPaymentOneParam().getCardNo());
            // 持卡人姓名 payType=2不可空
            transForm.setHolderName(payInfo.getXsFastPaymentOneParam().getHolderName());
            // 银行签约手机号 payType=2不可空
            transForm.setMobileNo(payInfo.getXsFastPaymentOneParam().getMobileNo());
            // 证件类型 payType=2不可空 暂仅支持1 身份证
            transForm.setIdentityType(payInfo.getXsFastPaymentOneParam().getIdentityType());
            // 证件号码 payType=2不可空
            transForm.setIdentityCode(payInfo.getXsFastPaymentOneParam().getIdentityCode());
        }
        // 绑卡协议号支付
        if (payInfo.getXsFastPaymentOneParam().getPayWay() == 3) {
            // 绑卡协议号 payType=3不可空
            transForm.setBindCardAgrNo(payInfo.getXsFastPaymentOneParam().getBindCardAgrNo());
            // 付款账户ID 协议支付时，必填
            transForm.setUserId(payInfo.getPayUserId());
        }
        // 收款方ID 消费交易时，填收款方ID 担保交易时，填商户ID 默认担保交易
        transForm.setReceiveUserId(payInfo.getReceiveUserId());
        // 商户异步通知地址
        transForm.setNotifyUrl(notifyUrl);
        // 商户用户IP
        transForm.setMerUserIp(IPHelper.getIpAddr());
        // 商品信息
        transForm.setGoodsInfo(payInfo.getBody());
        // 订单过期时长（单位：分钟）
        transForm.setOrderExpireTime("3");
        // 商户渠道进件ID
        transForm.setSubMerchantId(shopConfig.getHnaPay().getMerchantKjId());
        return transForm;
    }

    /**
     * 快捷支付确认
     *
     * @param payXsCountOrderParam payParam
     * @return T008TransForm
     * @throws Exception Exception
     */
    public T008TransForm getT008TransForm(PayXsCountOrderParam payXsCountOrderParam) throws Exception {
        T008TransForm transForm = new T008TransForm();
        transForm.setTranCode("T008");
        transForm.initCommonParams("T008", shopConfig.getHnaPay().getMerId(), payXsCountOrderParam.getXsFastPaymentTwoParam().getPayNo());
        transForm.setSubmitUrl(T008_SUBMIT_URL);
        transForm.setNcountOrderId(payXsCountOrderParam.getXsFastPaymentTwoParam().getNcountOrderId());
        transForm.setSmsCode(payXsCountOrderParam.getXsFastPaymentTwoParam().getSmsCode());
        transForm.setMerUserIp(IPHelper.getIpAddr());
        // 业务类型 03：消费（默认） 04：担保下单
        transForm.setBusinessType(payXsCountOrderParam.getBusinessType());
        if (ObjectUtil.isNotNull(payXsCountOrderParam.getXsFastPaymentTwoParam().getPaymentTerminalInfo())) {
            transForm.setPaymentTerminalInfo(payXsCountOrderParam.getXsFastPaymentTwoParam().getPaymentTerminalInfo());
        } else {
            String paymentTerminalInfo = "02|";
            transForm.setPaymentTerminalInfo(paymentTerminalInfo);
        }
        if (ObjectUtil.isNotNull(payXsCountOrderParam.getXsFastPaymentTwoParam().getReceiverTerminalInfo())) {
            transForm.setReceiverTerminalInfo(payXsCountOrderParam.getXsFastPaymentTwoParam().getReceiverTerminalInfo());
        } else {
            String receiverTerminalInfo = "02||CN|610000";
            transForm.setReceiverTerminalInfo(receiverTerminalInfo);
        }

        if (ObjectUtil.isNotNull(payXsCountOrderParam.getXsFastPaymentTwoParam().getDeviceInfo())) {
            transForm.setDeviceInfo(payXsCountOrderParam.getXsFastPaymentTwoParam().getDeviceInfo());
        } else {
            String deviceInfo = IPHelper.getIpAddr() + "||||||";
            transForm.setDeviceInfo(deviceInfo);
        }
        if (payXsCountOrderParam.getBusinessType().equals("04")) {
            if (ObjectUtil.isNull(payXsCountOrderParam.getDivideAcctDtlList())) {
                throw new Exception("分账信息为空!");
            }
            transForm.setDivideAcctDtl(payXsCountOrderParam.getDivideAcctDtlList());
            // 续费承担方id
            transForm.setFeeAmountUser(shopConfig.getHnaPay().getMerId());
            // 手续费内扣外扣 0：外扣（消费默认，担保时需单独申请）1：内扣（担保默认，消费时需单独申请）
            transForm.setFeeType("1");
        }
        return transForm;
    }

    /**
     * 新生支付退款
     *
     * @param refundInfo refundInfo
     * @return T005TransForm
     */
    public T005TransForm getT005TransForm(RefundInfoDto refundInfo, PayInfo payInfo) {
        T005TransForm transForm = new T005TransForm();
        transForm.setTranCode("T005");
        transForm.initCommonParams("T005", shopConfig.getHnaPay().getMerId(), refundInfo.getRefundSn());
        transForm.setSubmitUrl(T005_SUBMIT_URL);
        // 请求序列号
        transForm.setSerialId(refundInfo.getRefundSn());
        // 商户原始订单号
        transForm.setOrgMerOrderId(refundInfo.getPayNo());
        // 原订单支付下单请求时间
        transForm.setOrgSubmitTime(DateUtil.format(payInfo.getCreateTime(), DatePattern.PURE_DATETIME_PATTERN));
        // 原订单金额
        transForm.setOrderAmount(payInfo.getPayAmount().toString());

        transForm.setMerOrderId(refundInfo.getRefundSn());
        // 退款资金来源 1.新账通原路退款 2.商户现金户
        transForm.setRefundSource("1");
        // 退款目的地类型 1:原路退回
        transForm.setDestType("1");
        // 退款类型 1:全额退款 2：部分退款	03消费类型支持部分退，04担保下单内扣不支持部分退
        transForm.setRefundType("1");
        // 商户退款金额
        transForm.setRefundAmount(refundInfo.getRefundAmount().toString());
        // 异步通知地址
        transForm.setNotifyUrl(refundInfo.getNotifyUrl());
        // 备注
        transForm.setRemark("备注信息");
        return transForm;
    }

    /**
     * 交易查询
     *
     * @param payInfo payInfo
     * @return Q002TransForm
     */
    public Q002TransForm getQ002TransForm(PayInfoResultBO payInfo) {
        Q002TransForm transForm = new Q002TransForm();
        transForm.setTranCode("Q002");
        transForm.initCommonParams("Q002", shopConfig.getHnaPay().getMerId(), null);
        transForm.setSubmitUrl(Q002_SUBMIT_URL);
        transForm.setTranMerOrderId(payInfo.getPayNo());
        transForm.setQueryType("RECV");
        return transForm;
    }

    /**
     * 个人开户
     *
     * @param personalAccountOpenParam personalAccountOpenParam
     * @return R010TransForm
     */
    public R010TransForm getR010TransForm(PersonalAccountOpenParam personalAccountOpenParam) {
        R010TransForm transForm = new R010TransForm();
        transForm.setTranCode("R010");
        transForm.initCommonParams("R010", shopConfig.getHnaPay().getMerId(), null);
        transForm.setSubmitUrl(R010_SUBMIT_URL);
        transForm.setMerUserId(personalAccountOpenParam.getMerUserId());
        transForm.setMobile(personalAccountOpenParam.getMobile());
        transForm.setUserName(personalAccountOpenParam.getUserName());
        transForm.setCertNo(personalAccountOpenParam.getCertNo());
        return transForm;
    }

    /**
     * 商户系统上送平台商户编号，商户编号等信息查询用户状态和帐户余额。
     *
     * @param xsUserId xsUserId
     * @return Q001TransForm
     */
    public Q001TransForm getQ001TransForm(String xsUserId) {

        Q001TransForm transForm = new Q001TransForm();
        transForm.setTranCode("Q001");
        transForm.initCommonParams("Q001", shopConfig.getHnaPay().getMerId(), null);
        transForm.setSubmitUrl(Q001_SUBMIT_URL);
        transForm.setUserId(xsUserId);
        return transForm;
    }

    /**
     * 用户账户明细查询
     *
     * @param xsQueryParam xsQueryParam
     * @return Q004TransForm
     */
    public Q004TransForm getQ004TransForm(XsQueryParam xsQueryParam) {

        Q004TransForm transForm = new Q004TransForm();
        transForm.setTranCode("Q004");
        transForm.initCommonParams("Q004", shopConfig.getHnaPay().getMerId(), null);
        transForm.setSubmitUrl(Q004_SUBMIT_URL);
        transForm.setUserId(xsQueryParam.getXsUserId());
        transForm.setAcctType(xsQueryParam.getAcctType());
        transForm.setStartDate(xsQueryParam.getStartDate());
        transForm.setEndDate(xsQueryParam.getEndDate());
        transForm.setPageNum(ObjectUtil.isEmpty(xsQueryParam.getPageNum()) ? "1" : xsQueryParam.getPageNum());
        return transForm;
    }

    /**
     * 绑卡接口
     *
     * @param userXsCard userXsCard
     * @return R007TransForm
     */
    public R007TransForm getR007TransForm(UserXsCard userXsCard) {

        R007TransForm transForm = new R007TransForm();
        transForm.setTranCode("R007");
        transForm.initCommonParams("R007", shopConfig.getHnaPay().getMerId(), null);
        transForm.setSubmitUrl(R007_SUBMIT_URL);
        transForm.setCardNo(userXsCard.getCardNo());
        transForm.setHolderName(userXsCard.getHolderName());
        transForm.setMobileNo(userXsCard.getMobileNo());
        transForm.setIdentityType(userXsCard.getIdentityType());
        transForm.setIdentityCode(userXsCard.getIdentityCode());
        transForm.setUserId(userXsCard.getXsUserId());
        transForm.setMerUserIp(IPHelper.getIpAddr());
        return transForm;
    }

    /**
     * 绑卡确认
     *
     * @param ncountOrderId ncountOrderId
     * @param SmsCode       SmsCode
     * @return R008TransForm
     */
    public R008TransForm getR008TransForm(String ncountOrderId, String SmsCode) {

        R008TransForm transForm = new R008TransForm();
        transForm.setTranCode("R008");
        transForm.initCommonParams("R008", shopConfig.getHnaPay().getMerId(), null);
        transForm.setSubmitUrl(R008_SUBMIT_URL);
        transForm.setNcountOrderId(ncountOrderId);
        transForm.setSmsCode(SmsCode);
        transForm.setMerUserIp(IPHelper.getIpAddr());
        return transForm;
    }

    /**
     * 个人用户解绑
     *
     * @param xsUserId         xsUserId
     * @param oriBindCardAgrNo oriBindCardAgrNo
     * @return R009TransForm
     */
    public R009TransForm getR009TransForm(String xsUserId, String oriBindCardAgrNo) {
        R009TransForm transForm = new R009TransForm();
        transForm.setTranCode("R009");
        transForm.initCommonParams("R009", shopConfig.getHnaPay().getMerId(), null);
        transForm.setSubmitUrl(R009_SUBMIT_URL);
        transForm.setOriBindCardAgrNo(oriBindCardAgrNo);
        transForm.setUserId(xsUserId);
        return transForm;
    }

    /**
     * 收货确认接口
     *
     * @param orderId     支付订单号
     * @param divideId
     * @param divideDtlId
     * @return
     */
    public F001TransForm getF001TransForm(String orderId, String divideId, String divideDtlId) {

        F001TransForm transForm = new F001TransForm();
        transForm.setTranCode("F001");
        transForm.initCommonParams("F001", shopConfig.getHnaPay().getMerId(), null);
        transForm.setSubmitUrl(F001_SUBMIT_URL);
        transForm.setOrgMerOrderId(orderId);
        transForm.setDivideId(divideId);
        transForm.setDivideDtlId(divideDtlId);
        return transForm;
    }

    /**
     * 企业开户接口
     *
     * @param enterpriseAccountOpeningParam
     * @return
     */
    public R001TransForm getR001TransForm(EnterpriseAccountOpeningParam enterpriseAccountOpeningParam) {

        R001TransForm transForm = new R001TransForm();
        transForm.setTranCode("R001");
        transForm.initCommonParams("R001", shopConfig.getHnaPay().getMerId(), null);
        transForm.setSubmitUrl(R001_SUBMIT_URL);
        transForm.setMerUserId(enterpriseAccountOpeningParam.getShopId().toString());
        transForm.setUserName(enterpriseAccountOpeningParam.getUserName());
        transForm.setMobile(enterpriseAccountOpeningParam.getMobile());
        transForm.setCertType(enterpriseAccountOpeningParam.getCertType());
        transForm.setCertNo(enterpriseAccountOpeningParam.getCertNo());
        transForm.setCertValidate(enterpriseAccountOpeningParam.getCertValidate());
        transForm.setCardNo(enterpriseAccountOpeningParam.getCardNo());
        transForm.setBankCode(enterpriseAccountOpeningParam.getBankCode());
        transForm.setProvince(enterpriseAccountOpeningParam.getProvince());
        transForm.setCity(enterpriseAccountOpeningParam.getCity());
        transForm.setBranch(enterpriseAccountOpeningParam.getBranch());
        return transForm;
    }

    /**
     * 企业开户上送资料接口
     *
     * @param xsUserId     xsUserId
     * @param certFileType certFileType
     * @return
     */
    public R003TransForm getR003TransForm(String xsUserId, String certFileType) {

        R003TransForm transForm = new R003TransForm();
        transForm.setTranCode("R003");
        transForm.initCommonParams("R003", shopConfig.getHnaPay().getMerId(), null);
        transForm.setSubmitUrl(R003_SUBMIT_URL);
        transForm.setUserId(xsUserId);
        transForm.setCertFileType(certFileType);
        return transForm;
    }

    /**
     * 企业用户换卡接口
     *
     * @param enterpriseChangeCardParam enterpriseChangeCardParam
     * @return
     */
    public R002TransForm getR002TransForm(EnterpriseChangeCardParam enterpriseChangeCardParam) {

        R002TransForm transForm = new R002TransForm();
        transForm.setTranCode("R002");
        transForm.initCommonParams("R002", shopConfig.getHnaPay().getMerId(), null);
        transForm.setSubmitUrl(R002_SUBMIT_URL);
        transForm.setUserId(enterpriseChangeCardParam.getUserId());
        transForm.setBindCardAgrNo(enterpriseChangeCardParam.getBindCardAgrNo());
        transForm.setMobile(enterpriseChangeCardParam.getMobile());
        transForm.setCardNo(enterpriseChangeCardParam.getCardNo());
        transForm.setBankCode(enterpriseChangeCardParam.getBankCode());
        transForm.setProvince(enterpriseChangeCardParam.getProvince());
        transForm.setCity(enterpriseChangeCardParam.getCity());
        transForm.setBranch(enterpriseChangeCardParam.getBranch());
        return transForm;
    }

    /**
     * 企业信息修改接口
     *
     * @param enterpriseChangeInfoParam
     * @return
     */
    public R011TransForm getR011TransForm(EnterpriseChangeInfoParam enterpriseChangeInfoParam) {

        R011TransForm transForm = new R011TransForm();
        transForm.setTranCode("R011");
        transForm.initCommonParams("R011", shopConfig.getHnaPay().getMerId(), null);
        transForm.setSubmitUrl(R011_SUBMIT_URL);
        transForm.setUserId(enterpriseChangeInfoParam.getUserId());
        transForm.setCertNo(enterpriseChangeInfoParam.getCertNo());
        if (ObjectUtil.isNotEmpty(enterpriseChangeInfoParam.getUserName())) {
            transForm.setUserName(enterpriseChangeInfoParam.getUserName());
        }
        if (ObjectUtil.isNotEmpty(enterpriseChangeInfoParam.getMobile())) {
            transForm.setMobile(enterpriseChangeInfoParam.getMobile());
        }
        if (ObjectUtil.isNotEmpty(enterpriseChangeInfoParam.getCertValidate())) {
            transForm.setCertValidate(enterpriseChangeInfoParam.getCertValidate());
        }
        return transForm;
    }


    /**
     * 提交支付申请到新生
     *
     * @param base base
     * @return String
     * @throws Exception Exception
     */
    public Map<String, Object> post(BaseTransForm base) throws Exception {
        HnaPay hnaPay = shopConfig.getHnaPay();
        // 1，加载商户私钥
        PrivateKey privateKey = KeyUtils.loadPrivateKey(hnaPay.getMerPrivateKey(), hnaPay.getAlgorithm());
        // 4，获取加密字段的json串（明文）
        String encryptStr = base.getEncryptJsonStr();
        log.info("待加密字符串为：" + encryptStr);
        // 5，使用平台公钥进行rsa加密
        String msgCipherText = Base64Utils.encode(HnapaySign.encryptByPublicKey(encryptStr.getBytes(), hnaPay.getNcountPublicKey(), hnaPay.getAlgorithm())).replace("\n", "").replace("\r", "");
        log.info("加密后字符串为：" + msgCipherText);
        base.setMsgCiphertext(msgCipherText);
        // 6，使用商户私钥进行签名
        String signValue = Base64Utils.encode(HnapaySign.sign(privateKey, base.getCommonSignStr(), hnaPay.getSignAlgorithm())).replace("\n", "").replace("\r", "");
        log.info("签名后字符串为：" + signValue);
        base.setSignValue(signValue);
        // 7，构建提交至平台的请求参数
        Map<String, Object> reqMap = base.getCommonReqSignParams();
        reqMap.put("signValue", base.getSignValue());
        reqMap.put("charset", "1");
        log.info("提交字符串为：" + JSONUtil.toJsonStr(reqMap));
        String response;
        if (base.getSubmitUrl().startsWith("https://")) {
            HttpsTransport httpsTransport = new HttpsTransport();
            httpsTransport.setSendEncoding("UTF-8");
            httpsTransport.setUrl(base.getSubmitUrl());
            response = (String) httpsTransport.submit(reqMap);
        } else {
            HttpClientUtils httpClientUtils = new HttpClientUtils();
            response = httpClientUtils.submit(reqMap, base.getSubmitUrl());
        }
        log.info("响应字符串为：" + JSONUtil.toJsonStr(response));
        // 支付宝支付直接返回
        if(base.getTranCode().equals("T013")){
            Map<String,Object> map = new HashMap<>();
            map.put("option",response);
            return map;
        }
        // 8，返回参数转map
        Map<String, Object> responseMap = JSONUtil.toBean(response, Map.class);
        // 9，根据交易码构建不同接口验签明文串
        String verifyFieldStr = base.getVerifyDataByTranCode(base.getTranCode(), responseMap);
        log.info("验签明文字符串为：" + verifyFieldStr);
        // 10，使用平台公钥进行验签
        boolean verifyResult = HnapaySign.verify(hnaPay.getNcountPublicKey(), verifyFieldStr, responseMap.get("signValue").toString(), hnaPay.getSignAlgorithm(), hnaPay.getAlgorithm());
        log.info("验签结果为：" + verifyResult);
        if (verifyResult) {
            String respCode = responseMap.get("resultCode").toString(); // 应答码
            // 成功
            if (respCode.equals("0000") || respCode.equals("9999")) {
                return responseMap;
            } else {
                String errorMsg = responseMap.get("errorMsg").toString(); // 异常应答信息
                throw new Exception(errorMsg);
            }
        } else {
            throw new Exception("验签失败!");
        }
    }

    /**
     * hnaPay新生支付申请退款
     */
    public Boolean hnaPayRefundOrder(RefundInfoDto refundInfo, PayInfo payInfo) throws Exception {
        BaseTransForm base = getT005TransForm(refundInfo, payInfo);
        Map<String, Object> responseMap = post(base);
        String respCode = responseMap.get("resultCode").toString(); // 应答码
        log.info("退款请求响应参数 {}", JSONUtil.toJsonStr(responseMap));
        if (respCode.equals("0000")) {
            // 退款成功
            log.info("退款成功");
            return true;
        }
        log.error("调用新生退款，失败原因 {}", responseMap.get("errorMsg"));
        return false;
    }
}
